//
//  OAuthController.m
//  微博
//
//  Created by 沈艳男 on 15/11/13.
//  Copyright © 2015年 沈艳男. All rights reserved.
//

#import "OAuthController.h"
#import "UserAccount.h"
#import "NSArray+Log.h"

#import "NetWorkTools.h"
#import "SVProgressHUD.h"

@interface OAuthController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, copy) NSString *stringUrl;

@end

@implementation OAuthController

- (void)loadView
{
    [super loadView];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"登录新浪微博";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:(UIBarButtonItemStylePlain) target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:(UIBarButtonItemStylePlain) target:self action:@selector(automaticFill)];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view = self.webView;
    self.webView.delegate = self;
}

// 自动填充事件
- (void)automaticFill
{
    NSString *jsUser = @"document.getElementById('userId').value = 'synwyyx@163.com';";
    NSString *jspasswd = @"document.getElementById('passwd').value = '19880602';";
    NSString *js = [jsUser stringByAppendingString:jspasswd];
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

// 关闭按钮事件
- (void)close
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - webView代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 1.判断是否是回调地址,如果不是请继续加载
    NSString *urlString = request.URL.absoluteString;
    if (![urlString hasPrefix:(NSString *)[NetWorkTools sharedNetWorkToosl].redirect]) {
        return YES;
    }    
    
    // 2.判断如果是回调地址，检测 query 是否有 “code=”
    NSString *query = request.URL.query;
    if ([query hasPrefix:@"code="]) {
        // 3.取出code=后面的字符
        NSString *code = [query substringFromIndex:5];
        NSLog(@"获取code = %@", code);
        [self loadAccessToken:code userAccount:^(UserAccount *userAccount) {
            [self loadUserInfo:userAccount];
        }];
    }else {
        NSLog(@"取消登录");
    }
    return YES;
}

//获取AccessToken
- (void)loadAccessToken:(NSString *)code userAccount:(void(^)(UserAccount *))user
{
    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
    NSDictionary *params = @{@"client_id": [NetWorkTools sharedNetWorkToosl].client,
                             @"client_secret": [NetWorkTools sharedNetWorkToosl].secret,
                             @"grant_type": @"authorization_code",
                             @"code": code,
                             @"redirect_uri": [NetWorkTools sharedNetWorkToosl].redirect
                             };
    [[NetWorkTools sharedNetWorkToosl] requset:POST URLString:urlString parameters:params success:^(id success) {
        if (success) {
            NSDictionary *dict = (NSDictionary *)success;
            NSArray *array = [NSArray arrayWithObject:dict];
            NSMutableArray *mArray = [NSMutableArray array];
            for (NSDictionary *dict in array) {
                UserAccount *userAccount = [UserAccount usetAccountWithDict:dict];
                [mArray addObject:userAccount];
//                NSLog(@"用户模型%@", mArray);
                user(userAccount);
            }
        }
    } error:^(NSError *e) {
        NSLog(@"%@", e);
    }];
    
}

// 获取用户信息
- (void)loadUserInfo:(UserAccount *)account
{
    NSString *urlString = @"https://api.weibo.com/2/users/show.json";
    NSDictionary *params = @{@"access_token": account.access_token,@"uid": account.uid};
    [[NetWorkTools sharedNetWorkToosl] requset:GET URLString:urlString parameters:params success:^(id result) {
        NSDictionary *dict = (NSDictionary *)result;
        account.name = dict[@"name"];
        account.avatar_large = dict[@"avatar_large"];
        [UserAccount saveUserAccount:account];
        UserAccount *userAccount = [UserAccount readUserAccount];
        NSLog(@"解档数据打印%@", userAccount);
    } error:^(NSError *e) {
        NSLog(@"error%@", e);
    }];
}

- (UIWebView *)webView
{
    if (!_webView) {
        UIWebView *webView = [UIWebView new];
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.stringUrl]]];
        _webView = webView;
    }
    return _webView;
}

- (NSString *)stringUrl
{
    if (!_stringUrl) {
        NSString *stringUrl = [NSString stringWithFormat:@"%@", [NetWorkTools sharedNetWorkToosl].oauthUrl];
        _stringUrl = stringUrl;
    }
    return _stringUrl;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 转轮
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD show];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
}

@end
